package com.atguigu.yygh.cmn.service.impl;


import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-12-07
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictListener dictListener;


    @Cacheable(value = "dict")
    @Override
    public List<Dict> findDataChild(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> list = baseMapper.selectList(wrapper);
        for (Dict dict : list) {
            Long dictId = dict.getId();
            boolean isChild = this.isHasChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return list;
    }

    //数据字典导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置mime下载类型
            response.setContentType("application/vnd.ms-excel");
            //设置字符编码
            response.setCharacterEncoding("utf-8");
            //响应头，中文乱码处理
            String fileName = URLEncoder.encode("数据字典", "utf-8");
            response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");

            //查询dict表中的所有数据
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for (Dict dict : dictList) {

                //把dict 变成 dictEeVo
                DictEeVo dictEeVo = new DictEeVo();
                //工具类 dict => dictEeVo
                BeanUtils.copyProperties(dict, dictEeVo);
                dictEeVoList.add(dictEeVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictEeVoList);
        } catch (Exception e) {
            throw new YyghException(20001, "数据字典导出失败");
            //e.printStackTrace();
        }
    }


    //数据字典导入
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,
                            dictListener).sheet().doRead();
        } catch (Exception e) {
            throw new YyghException(20001, "数据字典上传失败");
        }
    }

    @Override
    public String getNameByCode(String dictCode, String value) {
/*        if(StringUtils.isEmpty(dictCode)){
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            if (dict == null){
                throw new YyghException(20001,"没有查询到数据");
            }
            return dict.getName();
        } else {
            //# 第一步 根据dict_code值查询医院等级层id值
            //SELECT * FROM dict WHERE dict_code='Hostype' # 10000
            QueryWrapper<Dict> dictCodeWrapper = new QueryWrapper<>();
            dictCodeWrapper.eq("dict_code",dictCode);
            Dict dictCodeObject = baseMapper.selectOne(dictCodeWrapper);

//            # 第二步 根据10000 + 1 两个值查询医院具体等级
//            SELECT * FROM dict WHERE parent_id=10000 AND VALUE=1
            QueryWrapper<Dict> dictWrapper = new QueryWrapper<>();
            dictWrapper.eq("parent_id",dictCodeObject.getId());
            dictWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(dictWrapper);
            return dict.getName();
        }*/

        if(StringUtils.isEmpty(dictCode)) { //value唯一，直接查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            if(dict == null) {
                throw new YyghException(20001,"没有查询到数据");
            }
            //返回编号对应名称
            return dict.getName();
        } else {//value不唯一，使用dictcode
            //# 第一步 根据dict_code值查询医院等级层id值
            //SELECT * FROM dict WHERE dict_code='Hostype' # 10000
            QueryWrapper<Dict> dictCodeWrapper = new QueryWrapper<>();
            dictCodeWrapper.eq("dict_code",dictCode);
            Dict dictCodeObject = baseMapper.selectOne(dictCodeWrapper);

//            # 第二步 根据10000 + 1 两个值查询医院具体等级
//            SELECT * FROM dict WHERE parent_id=10000 AND VALUE=1
            QueryWrapper<Dict> dictWrapper = new QueryWrapper<>();
            dictWrapper.eq("parent_id",dictCodeObject.getId());
            dictWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(dictWrapper);
            return dict.getName();
        }
    }

    @Override
    public List<Dict> selectAlldDataByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict1 = baseMapper.selectOne(wrapper);

        QueryWrapper<Dict> wrapperDict = new QueryWrapper<>();
        wrapperDict.eq("parent_id",dict1.getId());
        List<Dict> list = baseMapper.selectList(wrapperDict);
        return list;
    }

    private boolean isHasChildren(Long dictId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", dictId);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }
}
